import { Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { makeAutoObservable } from 'mobx';
import moment from 'moment';
import * as api from './api';

export default class MemberStore {
  _args = {
    search: {},
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  _args_logs = {
    search: {},
    pg: {
      page: 0,
      sort: ['ts;desc'],
      size: 10,
    },
  };
  total = 0;
  logs_total = 0;
  data = [];
  logs = [];
  modal = [];
  companiesNames = [];
  loading = false;
  loading_logs = false;
  _tabStatus = '1';

  _tableStatus = '-1'

  _tabItems = [
    { key: '-1', label: t`待审核` },
    { key: '0', label: t`未激活` },
    { key: '1', label: t`启用` },
    { key: '2', label: t`停用` },
    { key: '9', label: t`全部` },
  ];

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    search.status = [this._tableStatus];
    if (this._tableStatus == '9') {
      search.status = [0, 1, 2];
    }
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      const res = yield api.search({ search, pg });
      this.data = yield Promise.all(res.map(async (p) => {
        const { phone, companyName } = p;
        const vehicleCount = await api.getVehicleCount({ search: companyName ? { companyName } : { phone } });
        return { ...p, vehicleCount };
      }));
    } catch (error) {
      Message.error({ content: t`请求失败：${error}` });
      throw error;
    } finally {
      this.loading = false;
    }
  }

  * query_logs(pgInfo) {
    _.mergeWith(this._args_logs.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args_logs);
    if (!pg.sort?.length) delete pg.sort;
    this.loading_logs = true;
    try {
      this.logs_total = yield api.getLogsCount({ search });
      this.logs = yield api.getLogs({ search, pg });
    } catch (error) {
      Message.error({ content: t`请求失败：${error}` });
      throw error;
    } finally {
      this.loading_logs = false;
    }
  }

  * getGroup(args) {
    const res = yield api.getGroup(args);
    return res.map((p) => ({
      label: p.groupName,
      value: p.groupId,
    }));
  }

  * getDriver(args) {
    return yield api.getDriver(args);
  }

  * create(args) {
    yield api.create(args);
    yield this.query();
  }

  * update(args) {
    yield api.update(args);
    yield this.query();
  }

  * updateTakeStatus(args) {
    yield api.updateTakeStatus(args);
    yield this.query();
  }

  * remove(id) {
    yield api.remove(id);
    yield this.query();
  }

  * passCheck(id) {
    yield api.passCheck(id);
    yield this.query();
  }

  * get(id) {
    return yield api.get(id);
  }

  * params_search(args) {
    return yield api.search(args);
  }

  * getDicts(id) {
    const res = yield api.getDicts(id);
    return res.map((p) => ({ label: p.name, value: p.itemId }));
  }

  * getVehicles(args) {
    return yield api.getVehicle(args);
  }

  * importing(id, args) {
    return yield api.importing(id, args);
  }


  * filesUpload(args, data) {
    return yield api.filesUpload(args, data);
  }

  * getMemberDriver(args) {
    return yield api.getMemberDriver(args);
  }

  * updateVehicleFlag(args) {
    yield api.updateVehicleFlag(args);
    yield this.query();
  }

  * getCompaniesNames() {
    const res = yield api.getCompaniesNames();
    this.companiesNames = res.map(({ result }) => ({ label: result, value: result }));
  }

  * download() {
    try {
      const response = yield api.download();
      const fileData = response;
      const blob = new Blob(fileData?.map((buf) => Uint8Array.from(buf.data).buffer), { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = objectUrl;
      link.setAttribute('download', `成员白名单-${moment().format('YYYY-MM-DD')}.xlsx`);
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(link.href);
      link.remove();
    } catch (error) {
      console.error('下载文件失败:', error);
    }
  }

  customValidator(rule, value, callback) {
    const telRegex = /^[0-9]{4}$/;
    if (!value) {
      callback('必填');
    } else if (!telRegex.test(value)) {
      callback('长度必须4位');
    } else {
      callback(); // 校验通过
    }
  }

  /**
   * 校验该成员下是否存在订单
   * @param {*} args 成员数据
   * @returns boolean
   */
  async _verifyRemove(args) {
    if (!args?.username) {
      return { value: false };
    }
    try {
      const [order, task] = await Promise.all([
        api.orderCount({ search: { publisherId: args.username, orderStatus: [2, 3], groupIds: [args.groupId] } }),
        api.taskCount({ search: { orderTakerId: args.username, status: [1, 2], groupIds: [args.groupId] } }),
      ]);
      if (order === 0 && task === 0) {
        return { value: false };
      }
      let type = null;
      if (task > 0 && order > 0) {
        type = '2';
      } else if (task > 0) {
        type = '1';
      } else {
        type = '0';
      }
      return { value: true, type };
    } catch (error) {
      console.log('🚀 _ file: index.jsx:111 _ error:', error);
      throw error;
    }
  }

  * backupCodeUrl(groupId) {
    const res = yield api.getQRCode({
      path: `pages/backup/index?groupId=${groupId}`,
      env_version: global.ENV_VERSITION[global.ENV],
    });
    const blob = new Blob(
      res.map((buf) => Uint8Array.from(buf.data).buffer),
      {
        type: 'image/jpeg',
      },
    );
    const objectUrl = URL.createObjectURL(blob);
    return objectUrl;
  }

  * getLogs(args) {
    const res = yield api.getLogs(args);
    return res;
  }

  * updateMemberCompanyName(args) {
    return yield api.updateMemberCompanyName(args);
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get logs_pg() {
    return this._args_logs.pg;
  }

  set logs_pg(pg) {
    this.query_logs({ ...pg });
  }

  get logs_search() {
    this._args_logs.pg.page = 0;
    return this._args_logs.search;
  }

  set logs_search(search) {
    this._args_logs.pg.page = 0;
    this._args_logs.search = search;
    this.query_logs({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }

  get tab_Status() {
    return this._tabStatus;
  }

  set tab_Status(value) {
    this._tabStatus = value;
  }

  get table_Status() {
    return this._tableStatus;
  }

  set table_Status(value) {
    this._tableStatus = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }

  get api() {
    return api;
  }

  removeUnwantedProperties(obj) {
    const { groupId, groupName, id, takeOrderCount, issueOrderCount, points, initPoints, ...rest } = obj;
    return rest;
  }
}
